/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.yunhoo.fee.bean;

import com.yunhoo.fee.db.impl.DangHuiImpl;
import com.yunhoo.fee.model.DangHui;
import com.yunhoo.sys.util.common.LoginParam;
import com.yunhoo.sys.util.common.Null;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFFooter;
import org.apache.poi.hssf.usermodel.HSSFHeader;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CreationHelper;

@ManagedBean(name = "dangHuiTotal")
@SessionScoped
public class DangHuiTotalBean {

    private String iyear = "";
    private String iMonth = "";
    private List<SelectItem> iyearLi = new ArrayList<SelectItem>();
    private List<SelectItem> iMonthLi = new ArrayList<SelectItem>();
    private DangHui dang = new DangHui();
    private List<DangHui> detail = new ArrayList<DangHui>();

    public DangHuiTotalBean() {
        iyearLi = new ArrayList();
        for (int i = 2000; i < 2013; i++) {
            String str = String.valueOf(i);
            iyearLi.add(new SelectItem(str, str + "年"));
        }
        iMonthLi = new ArrayList();
        for (int m = 1; m < 13; m++) {
            String str = String.valueOf(m);
            iMonthLi.add(new SelectItem(str, str + "月"));
        }
    }

    public void selectTotal() {
        Double totalDang = 0d;
        Double totalHui = 0d;
        Double total = 0d;
        Map map = new HashMap();
        map.put("orgCode", LoginParam.getOrg().getCode());
        map.put("iyear", iyear);
        map.put("iMonth", iMonth);
        detail = DangHuiImpl.getTotal(map);
        if (!Null.check(detail)) {
            for (DangHui d : detail) {
                totalDang += d.getDangfei();
                totalHui += d.getHuifei();
            }
            dang.getDe().setName("合计");
            dang.setDangfei(totalDang);
            dang.setHuifei(totalHui);
            detail.add(dang);
        }
    }

    public void exportExcel() {
        HSSFWorkbook demoWorkBook = new HSSFWorkbook();
        HSSFSheet demoSheet = demoWorkBook.createSheet("个人党费会费");
        String[] excelColumns = initTabeleHeader();
        List<DangHui> rows = detail;

        HSSFHeader header = demoSheet.getHeader();
        header.setCenter("个人单据差旅费报销单列表");
        HSSFRow headerRow = demoSheet.createRow(0);
        for (int i = 0; i < excelColumns.length; i++) {
            HSSFCell headerCell = headerRow.createCell((short) i);
            //headerCell.setEncoding(HSSFCell.ENCODING_UTF_16);
            headerCell.setCellValue(excelColumns[i]);
        }
        //填充数据
        int rowIndex = 1;
        for (DangHui row : rows) {
            createTableRow(demoWorkBook, demoSheet, row, rowIndex);
            rowIndex++;
        }
        exportExcel(demoWorkBook, demoSheet);

    }
    //初始化表头信息

    public String[] initTabeleHeader() {
        String[] excelColumns = {"部门", "党费", "会费", "小计"};
        return excelColumns;
    }

    public static void createTableRow(HSSFWorkbook demoWorkBook, HSSFSheet demoSheet, DangHui eit, int rowIndex) {
        //创建第rowIndex行
        CreationHelper createHelper = demoWorkBook.getCreationHelper();
        HSSFCellStyle dstyle = demoWorkBook.createCellStyle();
        dstyle.setDataFormat(createHelper.createDataFormat().getFormat("yyyy-mm-dd"));//格式
        dstyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00"));



        HSSFCell cell = null;
        HSSFRow row = demoSheet.createRow(rowIndex);
        cell = row.createCell(0);
        cell.setCellValue(convertString(eit.getDe().getName()));
        cell = row.createCell(1);
        cell.setCellValue(convertDouble(eit.getDangfei()));
        cell.setCellStyle(dstyle);
        cell = row.createCell(2);
        cell.setCellValue(convertDouble(eit.getHuifei()));
        cell.setCellStyle(dstyle);
        cell = row.createCell(3);
        cell.setCellValue(convertDouble(Double.valueOf(eit.getDangfei() + eit.getHuifei())));
        cell.setCellStyle(dstyle);

    }

    private static String convertString(String str) {
        return str == null ? "" : str;
    }

    private static double convertDouble(Double num) {
        return num == null ? 0.0 : num;
    }

    public static void exportExcel(HSSFWorkbook demoWorkBook, HSSFSheet demoSheet) {
        try {
            String strfileName = "book.xls";
            FileOutputStream fos = null;
            //导出
            demoSheet.setGridsPrinted(true);//demoSheet
            HSSFFooter footer = demoSheet.getFooter();
            footer.setRight("Page " + HSSFFooter.page() + " of " + HSSFFooter.numPages());
            // 获得JSF上下文环境
            FacesContext context = FacesContext.getCurrentInstance();
            // 获得ServletContext对象
            ServletContext servletContext = (ServletContext) context.getExternalContext().getContext();
            // 取得文件的绝对路径
            String excelName = servletContext.getRealPath("/upload") + "/" + strfileName;//strfileName
            File exportFile = new File(excelName);
            fos = new FileOutputStream(exportFile);//fos
            demoWorkBook.write(fos);//demoWorkBook
            fos.close();

            FacesContext ctx = FacesContext.getCurrentInstance();
            ctx.responseComplete();
            HttpServletResponse httpServletResponse = (HttpServletResponse) ctx.getExternalContext().getResponse();
            ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
            httpServletResponse.setHeader("Content-disposition", "attachment; filename=" + strfileName);//strfileName
            httpServletResponse.setContentLength((int) exportFile.length());//exportFile
            httpServletResponse.setContentType("application/x-download");
            //httpServletResponse.setContentType("application/vnd.ms-excel");
            byte[] b = new byte[1024];
            int i = 0;
            FileInputStream fis = new java.io.FileInputStream(exportFile);
            while ((i = fis.read(b)) > 0) {
                servletOutputStream.write(b, 0, i);
            }
            servletOutputStream.flush();
            ctx.responseComplete();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getiMonth() {
        return iMonth;
    }

    public void setiMonth(String iMonth) {
        this.iMonth = iMonth;
    }

    public List<SelectItem> getiMonthLi() {
        return iMonthLi;
    }

    public void setiMonthLi(List<SelectItem> iMonthLi) {
        this.iMonthLi = iMonthLi;
    }

    public String getIyear() {
        return iyear;
    }

    public void setIyear(String iyear) {
        this.iyear = iyear;
    }

    public List<SelectItem> getIyearLi() {
        return iyearLi;
    }

    public void setIyearLi(List<SelectItem> iyearLi) {
        this.iyearLi = iyearLi;
    }

    public DangHui getDang() {
        return dang;
    }

    public void setDang(DangHui dang) {
        this.dang = dang;
    }

    public List<DangHui> getDetail() {
        return detail;
    }

    public void setDetail(List<DangHui> detail) {
        this.detail = detail;
    }
}
